"use client";
import React, { useEffect, useState, useMemo } from "react";
import "./index.scss";
import {
  message,
  DatePicker,
  ConfigProvider,
  Button,
  Select,
  Empty,
} from "antd";
import { ReloadOutlined } from "@ant-design/icons";
import type { Dayjs } from "dayjs";
import zhCN from "antd/locale/zh_CN";
import "dayjs/locale/zh-cn";

interface LogItem {
  type: string;
  message: string;
  data: number | string; // 统一为时间戳或时间字符串
}

interface ManageLogProps {}

const ManageLog: React.FC<ManageLogProps> = () => {
  const [data, setData] = useState<LogItem[]>([]);
  const [selectedType, setSelectedType] = useState<string>("all");
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [dateRange, setDateRange] = useState<[Dayjs | null, Dayjs | null]>([
    null,
    null,
  ]);

  const fetchData = async () => {
    try {
      setIsRefreshing(true);
      // 从本地存储读取日志数据
      const localLogs = localStorage.getItem("digitalHuman_logs");
      if (localLogs) {
        const logs = JSON.parse(localLogs);
        // 转换数据格式以匹配原有结构，统一时间格式
        const formattedLogs: LogItem[] = logs.map((log: any) => ({
          type: log.type || "unknown",
          message: log.message || "",
          data: log.timestamp || Date.now(),
        }));
        setData(formattedLogs);
        message.success("加载成功");
      } else {
        setData([]);
        message.info("暂无日志数据");
      }
    } catch (err) {
      console.error("获取日志失败:", err);
      message.error(
        `获取日志失败: ${err instanceof Error ? err.message : "未知错误"}`
      );
      setData([]);
    } finally {
      setIsRefreshing(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // 获取日志类型对应的中文描述和样式
  const getTypeInfo = (type: string) => {
    const typeMap: { [key: string]: { label: string; className: string } } = {
      start: { label: "启动", className: "type-start" },
      chat: { label: "对话", className: "type-chat" },
      active: { label: "活动", className: "type-active" },
      test: { label: "测试", className: "type-test" },
      error: { label: "关闭", className: "type-error" },
      recent: { label: "最近开启", className: "type-recent" },
      "recent-chat": { label: "最近对话", className: "type-recent-chat" },
      all: { label: "全部", className: "type-all" },
    };
    return typeMap[type] || { label: type, className: "" };
  };

  // 统一获取时间戳
  const getItemTimestamp = (item: LogItem): number => {
    if (typeof item.data === "number") {
      return item.data;
    }
    return new Date(item.data).getTime();
  };

  // 获取最后一次启动时间
  const getLastStartTime = (): number => {
    const startLogs = data.filter((item) => item.type === "start");
    return startLogs.length > 0
      ? getItemTimestamp(startLogs[startLogs.length - 1])
      : 0;
  };

  // 获取最后一次对话时间
  const getLastChatTime = (): number => {
    const chatLogs = data.filter((item) => item.type === "chat");
    return chatLogs.length > 0
      ? getItemTimestamp(chatLogs[chatLogs.length - 1])
      : 0;
  };

  // 筛选选项
  const filterOptions = [
    { value: "all", label: "全部" },
    { value: "start", label: "启动" },
    { value: "chat", label: "对话" },
    { value: "active", label: "活动" },
    { value: "error", label: "关闭" },
    { value: "recent", label: "最近开启" },
    { value: "recent-chat", label: "最近对话" },
  ];

  // 使用 useMemo 优化筛选数据计算
  const filteredData = useMemo(() => {
    let filtered = data;

    // 首先按类型筛选
    if (selectedType !== "all" && selectedType !== "delete") {
      if (selectedType === "recent") {
        const lastStartTime = getLastStartTime();
        filtered = data.filter(
          (item) => getItemTimestamp(item) >= lastStartTime
        );
      } else if (selectedType === "recent-chat") {
        const lastChatTime = getLastChatTime();
        filtered = data.filter(
          (item) => getItemTimestamp(item) >= lastChatTime
        );
      } else {
        filtered = data.filter((item) => item.type === selectedType);
      }
    }

    // 然后按日期范围筛选
    if (dateRange[0] && dateRange[1]) {
      const startTime = dateRange[0].valueOf();
      const endTime = dateRange[1].valueOf();
      filtered = filtered.filter((item) => {
        const itemTime = getItemTimestamp(item);
        return itemTime >= startTime && itemTime <= endTime;
      });
    }

    return filtered;
  }, [data, selectedType, dateRange]);

  // 处理日期范围变化
  const handleDateRangeChange = (
    dates: [Dayjs | null, Dayjs | null] | null,
    dateStrings: [string, string]
  ) => {
    setDateRange(dates || [null, null]);
  };

  // 格式化时间显示
  const formatTime = (item: LogItem): string => {
    const timestamp = getItemTimestamp(item);
    return new Date(timestamp).toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
      hour12: false,
    });
  };

  // 清空日志
  const handleClearLogs = () => {
    try {
      localStorage.removeItem("digitalHuman_logs");
      message.success("清空日志成功");
      fetchData();
    } catch (err) {
      console.error("清空日志失败:", err);
      message.error("清空日志失败");
    }
  };

  return (
    <ConfigProvider locale={zhCN}>
      <div className="manage_log">
        <div className="manage_log_header">
          <div className="manage_log_title">
            数字人日志{" "}
            <ReloadOutlined
              className={`refresh-icon ${isRefreshing ? "refreshing" : ""}`}
              onClick={fetchData}
            />
          </div>
          <div className="manage_prompt">
            最多存放500条日志 超出的会覆盖以前的日志 请及时清理
          </div>
          <div className="manage_log_filter">
            <Select
              value={selectedType}
              onChange={setSelectedType}
              style={{ width: 120, marginRight: "16px" }}
              options={filterOptions}
            />
            <DatePicker.RangePicker
              onChange={handleDateRangeChange}
              style={{ marginRight: "16px", width: "380px" }}
              showTime={{ format: "HH:mm" }}
              format="YYYY-MM-DD HH:mm"
              placeholder={["开始时间", "结束时间"]}
            />
            <Button type="primary" onClick={handleClearLogs}>
              清空日志
            </Button>
          </div>
        </div>
        <div className="manage_log_content">
          {filteredData.length > 0 ? (
            filteredData.map((item, index) => {
              const typeInfo = getTypeInfo(item.type);
              return (
                <div key={`${item.type}-${index}`} className="manage_log_item">
                  <div className={`type ${typeInfo.className}`}>
                    {typeInfo.label}
                  </div>
                  <div className="message">{item.message}</div>
                  <div className="time">{formatTime(item)}</div>
                </div>
              );
            })
          ) : (
            <Empty description="暂无日志数据" />
          )}
        </div>
      </div>
    </ConfigProvider>
  );
};

export default ManageLog;
